package cn.six1943.deepchat.module.ai.service.chatsession;

import cn.hutool.core.collection.CollUtil;
import cn.six1943.deepchat.module.ai.agent.AgentOutput;
import cn.six1943.deepchat.module.ai.agent.AiConstant;
import cn.six1943.deepchat.module.ai.agent.ChatHandler;
import cn.six1943.deepchat.module.ai.dal.mysql.chatsession.ChatMsgMapper;
import cn.six1943.deepchat.module.ai.util.SseUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Predicate;

import cn.six1943.deepchat.module.ai.controller.admin.chatsession.vo.*;
import cn.six1943.deepchat.module.ai.dal.dataobject.chatsession.ChatSessionDO;
import cn.six1943.deepchat.module.ai.dal.dataobject.chatsession.ChatMsgDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.six1943.deepchat.module.ai.dal.mysql.chatsession.ChatSessionMapper;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.six1943.deepchat.module.ai.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 会话 Service 实现类
 *
 * @author noday
 */
@Slf4j
@Service
@Validated
public class ChatSessionServiceImpl implements ChatSessionService {

    @Resource
    private ChatSessionMapper chatSessionMapper;
    @Resource
    private ChatMsgMapper chatMsgMapper;
    @Resource
    private Map<String, AgentService> agentServiceMap;

    @Override
    public Long createChatSession(ChatSessionSaveReqVO createReqVO) {
        // 插入
        ChatSessionDO chatSession = BeanUtils.toBean(createReqVO, ChatSessionDO.class);
        chatSessionMapper.insert(chatSession);
        // 返回
        return chatSession.getId();
    }

    @Override
    public void updateChatSession(ChatSessionSaveReqVO updateReqVO) {
        // 校验存在
        validateChatSessionExists(updateReqVO.getId());
        // 更新
        ChatSessionDO updateObj = BeanUtils.toBean(updateReqVO, ChatSessionDO.class);
        chatSessionMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChatSession(Long id) {
        // 校验存在
        validateChatSessionExists(id);
        // 删除
        chatSessionMapper.deleteById(id);

        // 删除子表
        deleteChatMsgBySessionId(id);
    }

    @Override
        @Transactional(rollbackFor = Exception.class)
    public void deleteChatSessionListByIds(List<Long> ids) {
        // 校验存在
        validateChatSessionExists(ids);
        // 删除
        chatSessionMapper.deleteByIds(ids);
    
    // 删除子表
            deleteChatMsgBySessionIds(ids);
    }

    private void validateChatSessionExists(List<Long> ids) {
        List<ChatSessionDO> list = chatSessionMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(CHAT_SESSION_NOT_EXISTS);
        }
    }

    private void validateChatSessionExists(Long id) {
        if (chatSessionMapper.selectById(id) == null) {
            throw exception(CHAT_SESSION_NOT_EXISTS);
        }
    }

    @Override
    public ChatSessionDO getChatSession(Long id) {
        return chatSessionMapper.selectById(id);
    }

    @Override
    public PageResult<ChatSessionDO> getChatSessionPage(ChatSessionPageReqVO pageReqVO) {
        return chatSessionMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ChatSessionDO> getChatSessionList(ChatSessionPageReqVO pageReqVO) {
        return chatSessionMapper.selectList(Wrappers.<ChatSessionDO>lambdaQuery().eq(ChatSessionDO::getCreator, getLoginUserId()));
    }

    // ==================== 子表（会话消息） ====================

    @Override
    public PageResult<ChatMsgDO> getChatMsgPage(PageParam pageReqVO, Long sessionId) {
        return chatMsgMapper.selectPage(pageReqVO, sessionId);
    }

    @Override
    public Long createChatMsg(ChatMsgDO chatMsg) {
        chatMsgMapper.insert(chatMsg);
        return chatMsg.getId();
    }

    @Override
    public void updateChatMsg(ChatMsgDO chatMsg) {
        // 校验存在
        validateChatMsgExists(chatMsg.getId());
        // 更新
        chatMsg.clean(); // 解决更新情况下：updateTime 不更新
        chatMsgMapper.updateById(chatMsg);
    }

    @Override
    public void deleteChatMsg(Long id) {
        // 删除
        chatMsgMapper.deleteById(id);
    }

	@Override
	public void deleteChatMsgListByIds(List<Long> ids) {
        // 删除
        chatMsgMapper.deleteByIds(ids);
	}

    @Override
    public ChatMsgDO getChatMsg(Long id) {
        return chatMsgMapper.selectById(id);
    }


    @Override
    @DSTransactional(rollbackFor = Exception.class)
    public SseEmitter sseChat(ChatRequest request) {
        ChatSessionDO session = chatSessionMapper.selectById(request.getSessionId());
        if (session == null) {
            session = new ChatSessionDO();
            session.setId(request.getSessionId());
            session.setBizType("");
            session.setBizId(null);
            session.setSummary("1");
            session.setStatus(request.isDebug()?4:5);
            chatSessionMapper.insert(session);
        }

        long tenantId = session.getTenantId();
        Long bizId = session.getBizId();
        Long sessionId = session.getId();
        String userId = session.getCreator();
        // HelpdeskBotEntity bot = botService.getOne(Wrappers.<HelpdeskBotEntity>lambdaQuery()
        //         .eq(HelpdeskBotEntity::getTenantId, tenantId)
        //         .eq(HelpdeskBotEntity::getHelpdeskId, helpdeskId)
        //         .eq(HelpdeskBotEntity::getIsDefault, 1), false);

        Long msgKey = IdWorker.getId();

        // 保存本次消息
        ChatMsgDO msg = new ChatMsgDO();
        msg.setSessionId(sessionId);
        msg.setRole("user");
        msg.setContent(request.getContent());
        Long msgId = createChatMsg(msg);
        // 调用ai
        SseEmitter emitter = SseUtil.getConn(String.valueOf(sessionId));
        try {
            chat2Agent(request, msgKey,
                    // beforeChat
                    (Void) -> {
                        return true;
                    },
                    // beforeChunk
                    (chunk) -> {
                        return true;
                    },
                    // onChunk
                    (chunk) -> {
                        // 发消息
                        try {
                            MsgChunkVO chunkVO = MsgChunkVO.builder()
                                    // .model("ddd")
                                    .id(String.valueOf(msgKey))
                                    .choices(List.of(MsgChoiceVO.builder().role("ai").content(chunk).build()))
                                    .build();
                            emitter.send(chunkVO);
                            log.info(chunk);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    },
                    // beforeComplate
                    (answer, output) -> {
                        return true;
                    },
                    // onComplate
                    (answer, output) -> {
                        try {
                            ChatMsgDO amsg = new ChatMsgDO();
                            amsg.setTenantId(tenantId);
                            amsg.setSessionId(sessionId);
                            amsg.setRole("ai");
                            amsg.setContent(JSON.toJSONString(List.of(ChatMsgContentVO.builder().type("text").content(answer).build())));
                            amsg.setId(msgKey);
                            chatMsgMapper.insert(amsg);

                            MsgChunkVO chunk = MsgChunkVO.builder()
                                    // .model("ddd")
                                    .id(String.valueOf(msgKey))
                                    .choices(List.of(MsgChoiceVO.builder().role("ai").content(answer).build()))
                                    .build();
                            emitter.send(SseEmitter.event().name("result").data(chunk));
                            log.info(amsg.getContent());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        } finally {
                            emitter.complete();
                        }
                    },
                    // 失败
                    (error) -> {
                        try {
                            if ("Invalid content-type: application/json".equals(error)) {
                                emitter.send("API调用失败");
                            } else {
                                emitter.send(error);
                            }
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        } finally {
                            emitter.complete();
                        }
                    });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

        }
        return emitter;
    }
    // @Override
    // @DSTransactional
    // public void imChat(ChatRequest request) {
    //     ChatSessionEntity session = chatSessionService.getById(request.getSessionId());
    //     String tenantId = session.getTenantId();
    //     Long helpdeskId = request.getBizId();
    //     HelpdeskBotEntity bot = botService.getOne(Wrappers.<HelpdeskBotEntity>lambdaQuery()
    //             .eq(HelpdeskBotEntity::getTenantId, tenantId)
    //             .eq(HelpdeskBotEntity::getHelpdeskId, helpdeskId)
    //             .eq(HelpdeskBotEntity::getIsDefault, 1), false);
    //     if (Func.isEmpty(bot)) {
    //         throw new ServiceException("默认机器人不存在");
    //     }
    //
    //     session.setBizId(request.getBizId());
    //
    //     Long sessionId = session.getId();
    //     Long userId = request.getUserId();
    //     Long msgKey = IdWorker.getId();
    //
    //     if (Func.isEmpty(request.getAssistantCompleteEntity())) {
    //         AssistantCompleteEntity assistantCompleteEntity = assistantCompleteMapper.selectOne(Wrappers.<AssistantCompleteEntity>lambdaQuery()
    //                 .eq(AssistantCompleteEntity::getAssistantId, request.getAgentId()));
    //         request.setAssistantCompleteEntity(assistantCompleteEntity);
    //     }
    //
    //     request.setTenantId(tenantId);
    //     request.setBotId(bot.getId());
    //     request.setAgentId(bot.getAgentId());
    //     request.setBizType(bot.getBizType());
    //     request.setSessionId(sessionId);
    //     request.setBizId(helpdeskId);
    //     request.setUserId(userId);
    //     assistantService.chat2Agent(request, msgKey,
    //             // 对话前
    //             (Void) -> {
    //                 //关键词 \情绪\用户重复提问转人工处理
    //                 boolean keyTestFlag = false;
    //                 try {
    //                     // 敏感词
    //                     log.info("itsm::imChat::匹配敏感词");
    //                     List<String> keyWords = new ArrayList<>();
    //                     BoolQuery.Builder bool = QueryBuilders.bool();
    //                     bool.must(m -> m.term(t -> t.field("assistantId").value(request.getAgentId())));
    //                     bool.must(m -> m.term(t -> t.field("type").value(2)));
    //                     SearchRequest req = new SearchRequest.Builder()
    //                             .index(AI_LEXICON_ + tenantId)
    //                             .query(q -> q.bool(bool.build()))
    //                             .source(s -> s.filter(f -> f.includes("name")))
    //                             .ignoreUnavailable(true)
    //                             .build();
    //
    //                     SearchResponse<JSONObject> searchResp = elasticsearchClient.search(req, JSONObject.class);
    //                     List<Hit<JSONObject>> hits = searchResp.hits().hits();
    //                     log.info("itsm::imChat::敏感词查询::{}", hits);
    //                     for (Hit<JSONObject> hit : hits) {
    //                         JSONObject source = hit.source();
    //                         String name = source.getString("name");
    //                         keyWords.add(name);
    //                     }
    //                     if (keyWords.size() > 0) {
    //                         log.info("itsm::imChat::敏感词::{}", StrUtil.join(",", keyWords));
    //                         long size = keyWords.stream().filter(k -> StrUtil.contains(request.getQuestion(), k)).count();
    //                         if (size > 0) {
    //                             log.info("itsm::imChat::监测到敏感词::{}", size);
    //
    //                             String text = Optional.ofNullable(request.getAssistantCompleteEntity())
    //                                     .map(AssistantCompleteEntity::getRefuseAnswer)
    //                                     .orElse("您的输入包含敏感词，请重试！");
    //                             chatMessageService.sendBotText(session, request.getBotId(), userId, text);
    //                             keyTestFlag = true;
    //                         }
    //                     }
    //                     if (keyTestFlag) {
    //                         return false;
    //                     }
    //                     // boolean flag = asyncTask.ifNeedCovertServiceStaff(session, request.getQuestion());
    //                     // if (flag) {
    //                     //     //触发转人工
    //                     //     asyncTask.asyncAllocatServiceStaff(session, null, CovertSource.AIAUTO.toString());
    //                     //     log.info("asyncAllocatServiceStaff flag{} complete", flag);
    //                     //     return false;
    //                     // }
    //                 } catch (Exception e) {
    //                     log.error("AI对话-对话前-转人工报错:session:" + sessionId, e);
    //                     if (keyTestFlag) {
    //                         return false;
    //                     }
    //                 }
    //
    //                 try {
    //                     List<HelpdeskAutoReplyEntity> autoReplayList = autoReplyService.list(Wrappers.<HelpdeskAutoReplyEntity>lambdaQuery()
    //                             .eq(HelpdeskAutoReplyEntity::getHelpdeskId, helpdeskId));
    //                     if (Func.isNotEmpty(autoReplayList)) {
    //                         JSONArray autoReplay = autoReplayList.get(0).getAutoReply();
    //                         for (int i = 0; i < autoReplay.size(); i++) {
    //                             JSONObject obj = autoReplay.getJSONObject(i);
    //                             String keyword = obj.getString("keyword");
    //                             if (Func.isNotBlank(keyword) && obj.containsKey("replay")) {
    //                                 if (StringUtil.containsIgnoreCase(request.getQuestion(), keyword)) {
    //                                     try {
    //                                         Thread.sleep(500);
    //                                     } catch (InterruptedException e) {
    //                                     }
    //                                     chatMessageService.saveAndSendByWs(session, bot.getId(), userId, ChatConstant.ROLE_AI, ChatConstant.MSG_TYPE_TEXT,
    //                                             MsgUtil.createTextMsg(obj.getString("replay")));
    //                                     return false;
    //                                 }
    //                             }
    //                         }
    //                     }
    //                 } catch (Exception e) {
    //                     log.error("AI对话-对话前-关键词回复报错:session:" + sessionId, e);
    //                 }
    //                 return true;
    //             },
    //             // beforeChunk
    //             (chunk) -> {
    //                 // if (asyncTask.isLastNoAnswer(session, chunk)) {
    //                 //     log.info("beforeChunk无答案回复拦截【{}】", chunk);
    //                 //     return false;
    //                 // }
    //                 return true;
    //             },
    //             // 输出
    //             (chunk) -> {
    //                 // 发消息
    //                 JSONObject content = new JSONObject();
    //                 content.put("chunk", chunk);
    //                 content.put("id", msgKey);
    //                 ChatMessageEntity message = chatMessageService.create(session, request.getBotId(),
    //                         ChatConstant.ROLE_AI, userId, ChatConstant.MSG_TYPE_STREAM, content);
    //                 message.setId(msgKey);
    //                 chatMessageService.sendByWs(message, userId);
    //
    //
    //             },
    //             // beforeComplate
    //             (answer, output) -> {
    //                 // try {
    //                 //     log.info("enter beforeComplate [{}]", answer);
    //                 //     //无答案,无回复处理
    //                 //     boolean flag2 = asyncTask.aiNoReplyAnswer(session, answer, answerResultType);
    //                 //     if (flag2) {
    //                 //         asyncTask.asyncAllocatServiceStaff(session, null, CovertSource.AIAUTO.toString());
    //                 //         log.info("beforeComplate无答案【{}】", answerResultType);
    //                 //         return false;
    //                 //     }
    //                 // } catch (Throwable t) {
    //                 //     log.error("消息附加业务异常", t);
    //                 //     if (Func.isBlank(answer)) {
    //                 //         return false;
    //                 //     }
    //                 // }
    //                 return true;
    //             },
    //             // 完成
    //             (answer, output) -> {
    //                 // 发给用户，im
    //                 JSONObject acontent = new JSONObject();
    //                 acontent.put("text", answer);
    //                 acontent.put("id", msgKey);
    //                 acontent.put("finish", true);
    //                 ChatMessageEntity amessage = chatMessageService.create(session, request.getBotId(),
    //                         ChatConstant.ROLE_AI, userId, ChatConstant.MSG_TYPE_STREAM, acontent);
    //                 amessage.setId(msgKey);
    //                 chatMessageService.save(amessage);
    //                 ChatMessageEntity msg = chatMessageService.sendByWs(amessage, userId);
    //                 try {
    //                     AiServiceRecordEntity record = new AiServiceRecordEntity();
    //                     Long id = IdWorker.getId();
    //                     //日志记录
    //                     msgService.saveAop(id,tenantId,userId);
    //                     record.setId(id);
    //                     record.setSessionId(sessionId);
    //                     record.setDeskId(helpdeskId);
    //                     record.setTenantId(tenantId);
    //                     record.setIssueId(0L);
    //                     record.setIssueCode(getIssueCode());
    //                     record.setGroupId(session.getObjectId());
    //                     record.setMsgId(msg.getId());
    //                     record.setRobotId(request.getBotId() + "");
    //                     record.setQuestionId(request.getMessageId());
    //                     record.setQuestionContent(request.getQuestion() != null ? request.getQuestion() : "");
    //                     record.setAnswerContent(answer);
    //                     record.setServiceId(userId);
    //                     record.setUserFeedback(0L);
    //                     record.setAdminTag("0");
    //                     record.setCreateTime(LocalDateTime.now());
    //                     aiServiceRecordService.save(record, id.toString());
    //                     //日志记录
    //                     msgService.endAop(id,tenantId,userId);
    //                 } catch (Exception e) {
    //                     log.error("记录机器人会话异常", e);
    //                 }
    //                 try {
    //                     // 缓存消息
    //                     HashOperations hashOperations = redisTemplate.opsForHash();
    //                     JSONObject jsonObject = new JSONObject();
    //                     jsonObject.put("msg", answer);
    //                     jsonObject.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    //                     hashOperations.put(tenantId + "_lastMsg", session.getId(), jsonObject.toString());
    //                     // 缓存未读消息数量
    //                     redisTemplate.opsForValue().increment(StringUtil.format(ChatConstant.UNREAD_MESSAGE, session.getObjectId(), userId));
    //                     // 刷新列表
    //                     chatSessionService.pushSession(session.getTenantId(), userId, session);
    //                 } catch (Exception e) {
    //                     log.error("处理消息异常", e);
    //                 }
    //                 try {
    //                     // log.info("ai answer[{}]", message.getContent().getString("text"));
    //                     // //无答案,无回复处理 ,机器人重复澄清转人工处理
    //                     // boolean flag1 = asyncTask.aiRepeatQuestion(session, message.getContent().getString("text"));
    //                     // boolean flag2 = asyncTask.aiNoReplyAnswer(session, message.getContent().getString("text"), answerResultType);
    //                     // log.info("aiRepeatQuestion flag1{} aiNoReplyAnswer flag2{} asyncAllocatServiceStaff start", flag1, flag2);
    //                     // if (flag1 || flag2) {
    //                     //     asyncTask.asyncAllocatServiceStaff(session, null, CovertSource.AIAUTO.toString());
    //                     //     log.info("aiRepeatQuestion flag1{} aiNoReplyAnswer flag2{} asyncAllocatServiceStaff complete", flag1, flag2);
    //                     // }
    //                 } catch (Throwable t) {
    //                     log.error("消息附加业务异常", t);
    //                 }
    //             },
    //             // 失败
    //             (error) -> {
    //                 //报错算无回复
    //                 try {
    //                     chatMessageService.sendBotText(session, request.getBotId(), userId, error);
    //                     // boolean flag2 = asyncTask.aiNoReplyAnswer(session, "", null);
    //                     // if (flag2) {
    //                     //     log.info("AI问答报错-转人工");
    //                     //     asyncTask.asyncAllocatServiceStaff(session, null, CovertSource.AIAUTO.toString());
    //                     // }
    //                 } catch (Exception e) {
    //                     log.error("AI对话-报错后-无回答转人工报错:session:" + sessionId, e);
    //                 }
    //             });
    // }

    // @Override
    // @DSTransactional(rollbackFor = Exception.class)
    // public SseEmitter sseChatDebug(ChatRequest request) {
    //     HelpdeskBotEntity bot = botService.getById(request.getBotId());
    //
    //     String tenantId = bot.getTenantId();
    //     Long deskId = bot.getHelpdeskId();
    //     Long sessionId = request.getSessionId();
    //     Long userId = AuthUtil.getUserId();
    //     Long msgKey = IdWorker.getId();
    //
    //     request.setTenantId(tenantId);
    //     request.setBotId(bot.getId());
    //     request.setAgentId(bot.getAgentId());
    //     request.setBizType(bot.getBizType());
    //     request.setSessionId(sessionId);
    //     request.setBizId(deskId);
    //     request.setUserId(userId);
    //
    //     AssistantCompleteEntity assistantCompleteEntity = new AssistantCompleteEntity();
    //     assistantCompleteEntity.setId(request.getAgentId());
    //     assistantCompleteService.procAssistantCompleteEntity(assistantCompleteEntity);
    //     request.setAssistantCompleteEntity(assistantCompleteEntity);
    //
    //     ChatSessionEntity sessionDto = new ChatSessionEntity();
    //     sessionDto.setTenantId(tenantId);
    //     sessionDto.setBizId(deskId);
    //     sessionDto.setObjectId(0L);
    //     sessionDto.setId(sessionId);
    //     sessionDto.setSessionType(4);
    //     sessionDto.setUserId(userId);
    //     // 调用ai
    //     SseEmitter emitter = SseUtil.getConn(String.valueOf(sessionId));
    //     try {
    //         assistantService.chat2Agent(request, msgKey,
    //                 // beforeChat
    //                 (Void) -> {
    //                     return true;
    //                 },
    //                 // beforeChunk
    //                 (chunk) -> {
    //                     return true;
    //                 },
    //                 // onChunk
    //                 (chunk) -> {
    //                     // 发消息
    //                     try {
    //                         emitter.send(chunk);
    //                         log.info(chunk);
    //                     } catch (IOException e) {
    //                         throw new RuntimeException(e);
    //                     }
    //                 },
    //                 // beforeComplate
    //                 (answer, output) -> {
    //                     return true;
    //                 },
    //                 // onComplate
    //                 (answer, output) -> {
    //                     JSONObject content = new JSONObject();
    //                     content.put("text", answer);
    //                     content.put("id", msgKey);
    //                     content.put("finish", true);
    //                     ChatMessageEntity amessage = chatMessageService.create(sessionDto, request.getBotId(),
    //                             ChatConstant.ROLE_AI, userId, ChatConstant.MSG_TYPE_STREAM, content);
    //                     amessage.setId(msgKey);
    //                     try {
    //                         emitter.send(SseEmitter.event().name("result").data(amessage));
    //                         log.info(amessage.getContent().toJSONString());
    //                     } catch (IOException e) {
    //                         throw new RuntimeException(e);
    //                     }
    //                     emitter.complete();
    //                 },
    //                 // 失败
    //                 (error) -> {
    //                     try {
    //                         if ("Invalid content-type: application/json".equals(error)) {
    //                             emitter.send("API调用失败");
    //                         } else {
    //                             emitter.send(error);
    //                         }
    //                     } catch (IOException e) {
    //                         throw new RuntimeException(e);
    //                     } finally {
    //                         emitter.complete();
    //                     }
    //                 });
    //     } catch (Exception e) {
    //         throw new RuntimeException(e);
    //     } finally {
    //         // emitter.complete();
    //     }
    //     return emitter;
    // }

    private void validateChatMsgExists(Long id) {
        if (chatMsgMapper.selectById(id) == null) {
            throw exception(CHAT_MSG_NOT_EXISTS);
        }
    }

    private void deleteChatMsgBySessionId(Long sessionId) {
        chatMsgMapper.deleteBySessionId(sessionId);
    }

	private void deleteChatMsgBySessionIds(List<Long> sessionIds) {
        chatMsgMapper.deleteBySessionIds(sessionIds);
	}


    public void chat2Agent(ChatRequest request,
                           Long streamKey,
                           Predicate<Void> beforeChat,
                           Predicate<String> beforeChunk,
                           Consumer<String> onChunk,
                           BiPredicate<String, AgentOutput> beforeComplate,
                           BiConsumer<String, AgentOutput> onComplate,
                           Consumer<String> onError) {


        AgentService agentService = agentServiceMap.get(AiConstant.agent.AgentType.fromCode(request.getBizType()).serviceName());
        String tenantId = request.getTenantId();
        if (request.getBizType() == 1) {
            // if (Func.isEmpty(request.getAssistantCompleteEntity())) {
            //     AssistantCompleteEntity assistantCompleteEntity = assistantCompleteMapper.selectOne(Wrappers.<AssistantCompleteEntity>lambdaQuery()
            //             .eq(AssistantCompleteEntity::getAssistantId, request.getAgentId()));
            //     request.setAssistantCompleteEntity(assistantCompleteEntity);
            // }
            // if (Objects.isEmpty(request.getAssistantCompleteEntity())) {
            //     String text = "默认机器人暂时不能提供服务";
            //     onChunk.accept(text);
            //     onComplate.accept(text, null);
            //     return;
            // }
        }

        boolean flag = beforeChat.test(null);
        if (flag) {
            StringBuffer answer = new StringBuffer();
            try {
                Long userId = request.getUserId();
                agentService.answerTheQuestion(request, new ChatHandler() {
                    @Override
                    public void onChunk(Long sessionId, Long messageId, String msg) {
                        boolean chunkFlag = beforeChunk.test(msg);
                        if (chunkFlag) {
                            answer.append(msg);
                            onChunk.accept(msg);
                        }
                    }

                    @Override
                    public void onStart(Long sessionId, Long messageId) {
                    }

                    @Override
                    public void onComplete(Long sessionId, Long messageId, AgentOutput output) {
                        // token使用量
                        List<AgentOutput.ModelUsage> usageList = output.getModels();
                        for (AgentOutput.ModelUsage modelUsage : usageList) {
                            // mqTemplate.convertAndSend(CloudProxyConstant.DESTINATION.CMP_TOPIC + CloudProxyConstant.HeadersTag.TOKEN_USAGE_EVENT,
                            //         TokenUsageEvent.of(ItsmEventConstant.TokenUsageType.HELPDESK_CHAT, tenantId, Long.valueOf(modelUsage.getModelId()), userId, streamKey,
                            //                 modelUsage.getInputTokens(), modelUsage.getOutputTokens(), modelUsage.getTotalTokens()));
                        }
                        String text = answer.toString();
                        boolean completeFlag = false;
                        try {
                            completeFlag = beforeComplate.test(text, output);
                        } catch (Exception e) {
                            log.error("beforeComplate error", e);
                        }
                        if (completeFlag) {
                            if (!request.isDebug()) {
                                // // 应用文档
                                // DocEvent docEvent = new DocEvent();
                                // docEvent.setType(1);
                                // docEvent.setDocId(2L);
                                // // 文档引用
                                // List<AgentOutput.DocReference> docReferences = output.getDocReferences();
                                // List<String> docs = docReferences.stream().map(AgentOutput.DocReference::getDocId).collect(Collectors.toList());
                                // if (ObjectUtil.isNotEmpty(docReferences)) {
                                //     mqTemplate.convertAndSend(CloudProxyConstant.DESTINATION.CMP_TOPIC + CloudProxyConstant.HeadersTag.DOC_USAGE_EVENT,
                                //             DocUsageEvent.of(tenantId, sessionId, streamKey, docs));
                                // }
                            }
                            onComplate.accept(text, output);
                        }
                    }

                    @Override
                    public void onError(Long sessionId, Long messageId, String error) {
                        onError.accept(error);
                    }

                    @Override
                    public boolean isStop() {
                        return false;
                    }
                });
            } catch (Exception e) {
                log.error("AI对话报错", e);
                // String error = Optional.ofNullable(request.getAssistantCompleteEntity())
                //         .map(AssistantCompleteEntity::getErrorAnswer)
                //         .filter(StrUtil::isNotBlank)
                //         .orElse("系统异常，请联系管理员");
                String error = "系统异常，请联系管理员";
                onError.accept(error);
            }
        }
    }

}